package com.keke.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.duansky.DataPreProcess;

/**
 * Servlet implementation class skyFileServlet
 */
@WebServlet("/skyFileServlet")
public class skyFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public skyFileServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String baseFilePath = getServletContext().getRealPath("/") + "duansky"
				+ File.separator + "data";

		// Check that we have a file upload requestss
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (!isMultipart) {
			return;
		}

		DiskFileItemFactory factory = new DiskFileItemFactory();

		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum size before a FileUploadException will be thrown
		upload.setSizeMax(20 * 1024 * 1024);

		List fileItems = null;
		try {
			fileItems = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// assume we know there are two files. The first file is a small
		// text file, the second is unknown and is written to a file on
		// the server
		Iterator i = fileItems.iterator();
		// String comment = ((FileItem) i.next()).getString();
		// System.out.println(comment);
		while (i.hasNext()) {
			FileItem fi = (FileItem) i.next();
			// filename on the client
			try {
				fi.write(new File(baseFilePath, "original_data.txt"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 生成各种分析文件
		if (KekeServlet.k == 0) {
			System.out.println("error");
			return;
		} else {
			DataPreProcess.analysisData(baseFilePath, KekeServlet.k, 50);
			System.out.println("write file success");
		}
	}

}
